package com.nuoniu.sibanyun.service.erp.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.erp.ErpTeam;
import com.nuoniu.sibanyun.mapper.erp.ErpTeamMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.IErpTeamService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * <p>
 * 班组 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2020-12-30
 */
@Service
public class ErpTeamServiceImpl extends ServiceImpl<ErpTeamMapper, ErpTeam> implements IErpTeamService {

    @Autowired
    private IErpAccountService accountService;

    @Override
    public Page<ErpTeam> pageList(Page page, ErpTeam erpTeam) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<ErpTeam> wrapper = new QueryWrapper();
        wrapper.eq("company_id", userInfo.getCompanyId());
        wrapper.orderByAsc("code");
        return this.page(page, wrapper);
    }

    @Override
    public void saveErpTeam(ErpTeam erpTeam) {
        UserInfo userInfo = UserThreadLocal.get();
        ErpTeam teamByCode = baseMapper.getByCode(userInfo.getCompanyId(), erpTeam.getCode());
        if(teamByCode != null && (erpTeam.getId() == null || !erpTeam.getId().equals(teamByCode.getId()))) {
            throw new NuoNiuException("编码不能重复");
        }

        ErpTeam teamByName = baseMapper.getByName(userInfo.getCompanyId(), erpTeam.getName());
        if(teamByName != null && (erpTeam.getId() == null || !erpTeam.getId().equals(teamByName.getId()))) {
            throw new NuoNiuException("名称不能重复");
        }

        if(erpTeam.getId() == null) {
            erpTeam.setAccountId(accountService.getCurrentAccountId());
            erpTeam.setCompanyId(userInfo.getCompanyId());
        }
        this.saveOrUpdate(erpTeam);
    }
}
